<template>
  <div>
  <!--  主页导航栏-->
  <div class="container">
    <div class="left1">
      <span style="font-size: 20px">去{{endaddress}}</span><br>
      <span style="font-size: 12px">全程
        <span style="flood-color: violet">{{driverLong}}</span>
        公里 全程约<span style="flood-color: violet">{{driverTime}}</span>
        分钟</span>
    </div>
    <div class="right1">
      <a @click="go()">
      <img src="@/assets/导航.png" style="width: 80px;height: 50px;"/>
      <br>
      <p>导航</p>
      </a>
    </div>
  </div>
  <van-divider style="background-color: black;margin-top: -2px"></van-divider>
  <div>
    <span style="line-height: 20px;text-align: left;display: inline-block">{{this.order.orderTime.takeorderTime}}</span>
  </div>

  <van-sticky :offset-top="880" z-index="100">
    <div class="custom-layout">
      <div class="custom-item" style="width: 300px;height: 50px"  >
        <van-button style="width: 200px;height: 40px;background-color: #409EFF;border-radius: 30px;" @click="re()">返回</van-button>
      </div>
    </div>
  </van-sticky>


  <van-sticky :offset-top="750" z-index="100">
    <div class="main-container">
      <div class="sub-box left-container">
        <div>
          <p style="font-size: 20px" class="bold-text">{{ this.userPhone }}</p>
          <p >尾号</p>
        </div>
      </div>
      <div class="sub-box middle">
        <div class="theOrderInderBoxFirst container1">
          <div class="radioBox"></div>
          <div class="" style="width: 150px;margin-left: -50px">{{startaddress}}</div>
        </div>
        <div class="theOrderInderBoxSecond container1">
          <div class="radioBox"></div>
          <div class="" style="width: 150px;margin-left: -50px">{{endaddress}}</div>
        </div>
      </div>
      <div class="sub-box right-container">
        <van-icon @click="lt()" class="icon" name="chat-o" />
        <a @click="callPhone(phoneNum)"><van-icon class="icon" name="phone" /></a>
      </div>
    </div>
  </van-sticky>
  <div id="showMap"  style="margin-top: -160px;z-index: 1"></div>

</div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import StartIcon from "@/assets/导航起点.png"



export default {
  data() {

    return {
      startTime:Date.now(), // 记录起始时间
      reminderIntervals: [15 * 60 * 1000, 30 * 60 * 1000, 60 * 60 * 1000], // 15分钟、30分钟和1小时的时间间隔
      timers: [], // 用于存储定时器ID
      map: null,
      order:{

      },
      user:{

      },
      driverTime: null,
      driverLong: null,
      startaddress:"",
      endaddress:"",
      userPhone:"",
      phoneNum:"",
      // 开始的经纬度
      startLatitudeAndLongitude: "",
      // 结束的经纬度
      endLatitudeAndLongitude: "",
    };
  },
  mounted() {
    this.initAMap();
    // 组件挂载后启动提醒
    this.startReminders();
  },
  unmounted() {
    this.map.destroy();
  },
  created() {
  this.getorder();
  this.findPhone();
},
  beforeDestroy() {
    // 组件销毁前停止提醒
    this.stopReminders();
  },

  methods: {
    //聊天跳转
    lt(){
      this.$router.push({path:'/DriverChatMessage',query:{userId: this.order.orderInformation.userId}})
    },
    startReminders() {
      this.reminderIntervals.forEach((interval) => {
        const reminderTime = this.startTime+ interval; // 计算提醒时间
        const delay = reminderTime - Date.now(); // 计算初次提醒的延迟
        if (delay > 0) {
          const timerId = setTimeout(() => {
            this.triggerReminder(interval);
            this.scheduleNextReminder(interval);
          }, delay);

          this.timers.push(timerId);
        }
      });
    },
    scheduleNextReminder(interval) {
      // 在当前提醒的基础上再设置下一个提醒
      const timerId = setInterval(() => {
        this.triggerReminder(interval);
      }, interval);

      this.timers.push(timerId);
    },
    triggerReminder(interval) {
      // 实现提醒逻辑
      alert(`提醒：已经过去了${interval / (60 * 1000)}分钟！`);
    },
    stopReminders() {
      // 清除所有定时器
      this.timers.forEach(timerId => clearTimeout(timerId));
      this.timers = [];
    },

    // 获取乘客号码
    findPhone(){
         this.phoneNum=this.order.orderInformation.passengerPhone;
        this.userPhone=this.phoneNum.substring(7);
    },
    //返回
    re(){
      this.$router.go(-1);
    },
    //点击导航进行接单
    go(){
      this.$router.push({
        path: '/itineraryDetails',
        query: {orderId:this.order.orderInformation.id}
      })
    },
    // 获取订单信息
    async getorder(){
      this.order=this.$route.query.order;
      this.startLatitudeAndLongitude=this.order.orderInformation.startingPoint;
      this.endLatitudeAndLongitude=this.order.orderInformation.destination;
    },

    //拨打电话
    callPhone (phoneNum) {
      window.location.href = 'tel://' + phoneNum
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: this.$cod,
      };
      let self = this;
      AMapLoader.load({
        key: this.$key, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale","AMap.Geocoder"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
          .then((AMap) => {
                var map = new AMap.Map("showMap", {
                  // 设置地图容器id
                  viewMode: "3D", // 是否为3D地图模式
                  zoom: 11, // 初始化地图级别
                  center: [116.397428, 39.90923],//地图显示中心点坐标
                });
                var icon = new AMap.Icon({
                  // 图标尺寸 ===> new AMap.Size(宽, 高)
                  size: new AMap.Size(80, 50),
                  // Icon图片
                  image: StartIcon,
                  // 根据所设置的大小拉伸或压缩图片 ===> new AMap.Size(宽, 高)
                  imageSize: new AMap.Size(50, 50)
                });
                // 逆地址
                var geocoder = new AMap.Geocoder({
                  city: "", //城市设为北京，默认：“全国”
                });
                //添加点标记
                var marker = new AMap.Marker({
                  // 在这个里面需要设置偏移度,值应和图标的大小一致,如不设置,则会出现定位点随着地图缩略的变化而变化
                  offset: new AMap.Pixel(-50, -50),
                  icon
                });
                map.add(marker); //添加到地图
                AMap.plugin(
                    ["AMap.ToolBar", "AMap.Driving", "AMap.Polyline", "AMap.Marker","AMap.Geolocation"],
                    function() {
                      var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                        timeout: 10000, // 设置定位超时时间，默认：无穷大
                        offset: [10, 20],  // 定位按钮的停靠位置的偏移量
                        zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                        position: 'RB', //  定位按钮的排放位置,  RB表示右下

                      });
                      map.addControl(geolocation);
                      geolocation.getCurrentPosition(function(status,result){
                        if(status=='complete'){
                          onComplete(result)
                        }else{
                          onError(result)
                        }
                      });
                      function onComplete (data) {
                        self.position = data.position + "";
                        console.log(self.position);
                        // self.endLatitudeAndLongitude=data.position;
                        console.log("定位结果:" + data.position);
                        console.log("定位类别:" + data.location_type);
                        console.log("精度:" + data.accuracy + "米");
                        console.log("是否经过偏移:" + data.isConverted);
                        // document.getElementById('status').innerHTML='定位成功'
                        var str = [];
                        str.push('定位结果：' + data.position);
                        str.push('定位类别：' + data.location_type);
                        if (data.accuracy) {
                          str.push('精度：' + data.accuracy + ' 米');
                        }//如为IP精确定位结果则没有精度信息
                        str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
                        // this.position=str;
                        // document.getElementById('result').innerHTML = str.join('<br>');

                      }
                      function onError (data) {
                        console.log("定位失败")
                        console.log("失败原因排查信息:" + data.message)
                        // 定位出错
                      }
                      //异步同时加载多个插件
                      var toolbar = new AMap.ToolBar();
                      map.addControl(toolbar);
                      var driving = new AMap.Driving({
                        map: map,
                      }); //驾车路线规划
                      // var在函数作用外,否则无法调用
                      var startTranse = self.startLatitudeAndLongitude.split(",");
                      var endTranse = self.endLatitudeAndLongitude.split(",");
                      driving.search(
                          // 因地址值用2214.111的经纬度,所以需要格式转换
                          new AMap.LngLat(parseFloat(startTranse[0]), parseFloat(startTranse[1])),
                          new AMap.LngLat(parseFloat(endTranse[0]), parseFloat(endTranse[1])),
                          function(status, result) {
                            if (status === "complete") {
                              console.log("绘制驾车路线完成", result);
                              // 在这一块需要设置加时时间和大概的路程多少公里,用四舍五入的方式计算
                              self.driverTime = Math.round(result.routes[0].time / 60);
                              self.driverLong = Math.round(result.routes[0].distance / 1000);

                              // 逆地理编码获取地址信息
                              var start = self.startLatitudeAndLongitude.split(",");
                              var end = self.endLatitudeAndLongitude.split(",");
                              // 寻找开始地址的方法
                              geocoder.getAddress(start, function(status, result) {
                                if (status === 'complete' && result.regeocode) {
                                  self.startaddress = result.regeocode.formattedAddress;
                                } else {
                                  console.log("获取开始地址失败");
                                }
                              });
                              // 寻找结束地址的方法
                              geocoder.getAddress(end, function(status, result) {
                                if (status === 'complete' && result.regeocode) {
                                  self.endaddress = result.regeocode.formattedAddress;
                                  console.log(result.regeocode + "end");
                                } else {
                                  console.log("获取结束地址失败");
                                }
                              });
                            } else {
                              console.log("获取驾车数据失败：" + result);
                            }
                          }
                      );
                    }
                );
              }
          )
    },
  },
};
</script>

<style scoped>
.icon {
  font-size: 50px; /* 设置图标尺寸 */
  display: flex;
  justify-content: center; /* 水平居中对齐 */
  align-items: center; /* 垂直居中对齐 */
  margin-top: 20px;
}

/* 可能需要为 <van-icon> 元素添加额外的样式 */
van-icon {
  width: 100%; /* 确保图标占据整个空间 */
  height: 100%; /* 确保图标占据整个空间 */
}

.radioBox{
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: green ;
  margin-left: -20px;
}
.van-ellipsis111{
  margin-left: -50px;
}
.main-container {

  margin-left: 5%;
  margin-right: 5%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background-color: white;
  padding: 10px;
}

.sub-box {
  flex: 1;

}

.sub-box.middle {
  flex: 3;
}

.left-container {
  display: flex;
  justify-content: center; /* 水平居中对齐 */
  align-items: center; /* 垂直居中对齐 */
  flex-direction: column;

}

.right-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bold-text {
  font-weight: bold;
}
.custom-layout {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 10px;
}

.custom-item {
  width: 30%; /* 调整宽度 */
  padding: 5px; /* 调整内边距 */
  height: 30px;
  margin-left: 40px;
  margin-right: 40px;
  border-radius: 20px;

}

.custom-item:nth-child(2) {
  background-color: lightgreen;
}

#showMap{
  width: 100%;
  height: 800px;
}
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: lightgray;
  padding: 10px;
}
.theOrderInderBoxFirst{
  background-color: white;
}
.theOrderInderBoxSecond{
  background-color: white;
}

.container1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left1 {
  padding: 10px;
}

.right1 {
  padding: 10px;
}
</style>
